<script>
import { computed, defineComponent } from 'vue'
import FanIcon from '../icon/icon.vue'
import { createNamespace, transformSize } from '../utils'

export default defineComponent({
	name: createNamespace('Checkbox')[0],
	options: {
		// https://uniapp.dcloud.io/matter.html#mp
		virtualHost: true
	},
	components: { FanIcon },
	props: {
		modelValue: {
			type: Boolean,
			default: false
		},
		size: {
			type: [String, Number],
			default: '24px'
		},
		color: {
			type: String
		},
		iconColor: String,
		disabled: {
			type: Boolean,
			default: false
		}
	},
	emits: ['update:modelValue', 'change'],
	setup(props, { emit }) {
		const theStyle = computed(() => {
			const { color } = props
			let s = ''
			if (color) s += `--fan-checkbox-active-color:${color};`
			return s
		})
		const iSize = computed(() => transformSize(props.size))

		const toggle = () => {
			const val = !props.modelValue
			emit('update:modelValue', val)
			emit('change', val)
		}

		return { theStyle, iSize, toggle, iconColor: props.iconColor }
	}
})
</script>

<template>
	<div :style="theStyle" class="fan-checkbox"
		:class="{ 'fan-checkbox--disabled': disabled, 'fan-checkbox--checked': modelValue }" @click="toggle">
		<div class="fan-checkbox__i" :style="{ width: iSize, height: iSize }">
			<FanIcon name="check" :size="`calc(${iSize} * 0.8)`"
				:color="disabled ? '#c8c9cc' : iconColor ? iconColor : '#fff'"
				:style="{ visibility: modelValue ? 'visible' : 'hidden' }" />
		</div>
	</div>
</template>

<style lang="less">
.fan-checkbox {
	--fan-checkbox-active-color: var(--fan-primary-color);

	cursor: pointer;
	-webkit-tap-highlight-color: transparent;

	&--checked {
		.fan-checkbox__i {
			background: var(--fan-checkbox-active-color);
			border: 0;
		}
	}

	&--disabled {
		background: #ebedf0;
		cursor: not-allowed;
	}

	&__i {
		line-height: 1;
		display: inline-flex;
		justify-content: center;
		align-items: center;
		background: transparent;
		transition: background 0.2s;
		border: 1px solid #c8c9cc;
		border-radius: 50%;
		box-sizing: border-box;
	}
}
</style>